package adb;
import static adb.ADBView.jScrollPaneDevice;
import static adb.ADBView.jTextAreaStatus;
import static adb.ADBView.jTreeDevice;
import static adb.ADBView.listApps;
import static adb.ADBView.output;
import static adb.ADBView.pathDeviceFileOnClick;
import static adb.ADBView.ParentpathDeviceFileOnClick;
import static adb.ADBView.path;
import static adb.screenShot.bridge;
import static adb.ADBView.loadTreeFileDeviceSuccessStatus;
import com.android.ddmlib.AndroidDebugBridge;
import com.android.ddmlib.FileListingService;
import com.android.ddmlib.IDevice;
import com.android.ddmlib.SyncService;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.swing.JTree;
import javax.swing.SwingWorker;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

public class loadTreeFileDevice extends SwingWorker<Void, String>{
            IDevice device;
            FileListingService service;

    @Override
    protected Void doInBackground() throws Exception {
        AndroidDebugBridge.init(false /* debugger support */);
        int count = 0;
        loadTreeFileDeviceSuccessStatus=0;
        while (bridge.hasInitialDeviceList() == false) {
            try {
                Thread.sleep(2000);
                count++;
                jTextAreaStatus.setText(output = output + "Connect to device..." + count + "\n");
            } catch (InterruptedException ex) {
                output = output + ex + "----ex18\n";
                jTextAreaStatus.setText(output);
            }
            if (count > 3) {
                output = output + "Timeout getting device list!\n";
                jTextAreaStatus.setText(output);
                return null;
            }
        }
        
        AndroidDebugBridge bridge = AndroidDebugBridge.createBridge();
        IDevice[] devices = bridge.getDevices();
        IDevice device0 = devices[0];
        loadTreeFileDevice(device0);
        listApps.setVisible(false);
        listApps.setEnabled(false);
        jTreeDevice.setVisible(true);
        jTreeDevice.setEnabled(true);
        jScrollPaneDevice.setViewportView(jTreeDevice);
        loadTreeFileDeviceSuccessStatus=1;
        return null;
    }
    
    private class FileTreeNode extends DefaultMutableTreeNode {
                String name;
                String pathFileTN;
                public FileTreeNode(String name, String path) {
                        super(name);
                        this.name = name;
                        this.pathFileTN = path;
                }    
        }
    private class FolderTreeNode extends LazyMutableTreeNode {
                String name;
                String pathFolerTN;
                public FolderTreeNode(String name, String path) {
                        this.name = name;
                        this.pathFolerTN = path;
                }
                @Override
                public void initChildren() {
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        try {
                                String cmd = "ls -l "+pathFolerTN;
                                device.executeShellCommand(cmd, new OutputStreamShellOutputReceiver(bos));
                                String s = new String(bos.toByteArray(),"UTF-8");
                                String[] entries = s.split("\r\n");
                                for(int i=0; i<entries.length; i++) {
                                        String[] data = entries[i].split(" ");
                                        if(data.length < 4)
                                                continue;
                                        /*
                                        for(int j=0; j<data.length; j++) {
                                                System.out.println(j+" = "+data[j]);
                                        }
                                        */
                                        String attribs = data[0];
                                        boolean directory = attribs.startsWith("d");
                                        String name = data[data.length-1];
                                        if(directory)
                                                add(new FolderTreeNode(name, pathFolerTN + name + "/"));
                                        else
                                                add(new loadTreeFileDevice.FileTreeNode(name, pathFolerTN + name));
                                }
                        } catch(IOException ex) {
                            output=output+ex+"\n";
                                jTextAreaStatus.setText(output);
                        }
                }
                public String toString() {
                        return name;
                }
        }
    public void loadTreeFileDevice(IDevice device) {
                this.device = device;
                this.service =  device.getFileListingService();
                jTreeDevice = new JTree(new DefaultMutableTreeNode("Test"));
                jTreeDevice.setModel(new DefaultTreeModel(new loadTreeFileDevice.FolderTreeNode("/","/")));
                jTreeDevice.setRootVisible(true);
                
                device.getFileListingService().getChildren(service.getRoot(), false, new FileListingService.IListingReceiver() {
                        
                        public void setChildren(FileListingService.FileEntry arg0, FileListingService.FileEntry[] arg1) {
                                // TODO Auto-generated method stub
                                //System.out.println("setChildren "+arg1.length);
                                
                        }
                        
                        public void refreshEntry(FileListingService.FileEntry arg0) {
                                
                                //System.out.println("refresh"+arg0.getName());
                        }
                });
                
//                jTreeDevice.addMouseListener(new MouseAdapter() {
//                        @Override
//                        public void mouseClicked(MouseEvent e) {
////                                if(e.getClickCount() == 2) {
//                                        TreePath tp = jTreeDevice.getPathForLocation(e.getX(), e.getY());
//                                        if(tp == null)
//                                                return;
//                                        if(!(tp.getLastPathComponent() instanceof loadTreeFileDevice.FileTreeNode))
//                                                return;
//                                        loadTreeFileDevice.FileTreeNode node = (loadTreeFileDevice.FileTreeNode)tp.getLastPathComponent();
////                                        launchFile(node);
//                                        pathDeviceFileOnClick=node.pathFileTN;
//                                        //System.out.print(node.pathFileTN+"\n");
////                                }
//                        }
//                });
                jTreeDevice.addTreeSelectionListener(new TreeSelectionListener() {

                    public void valueChanged(TreeSelectionEvent e) {
                        TreePath tp = e.getPath();
                        if(tp == null)
                            return;
                        if(!(tp.getLastPathComponent() instanceof loadTreeFileDevice.FileTreeNode))
                            return;
                            loadTreeFileDevice.FileTreeNode node = (loadTreeFileDevice.FileTreeNode)tp.getLastPathComponent();
    //                      launchFile(node);
                            pathDeviceFileOnClick=node.pathFileTN;
                            
                        
//                        TreePath tpParent = e.getPath();
//                        if(tpParent == null)
//                            return;
//                        if(!(tpParent.getLastPathComponent() instanceof loadTreeFileDevice.FolderTreeNode))
//                            return;
//                        loadTreeFileDevice.FolderTreeNode FolderPath = (loadTreeFileDevice.FolderTreeNode)tpParent.getLastPathComponent();
                        ParentpathDeviceFileOnClick = e.getPath().toString();
                        ParentpathDeviceFileOnClick=ParentpathDeviceFileOnClick.replace("[", "");
                        ParentpathDeviceFileOnClick=ParentpathDeviceFileOnClick.replace("]", "");
                        ParentpathDeviceFileOnClick=ParentpathDeviceFileOnClick.replace(", ", "/");
                        //ParentpathDeviceFileOnClick=path.pathFolerTN;
                        //ParentpathDeviceFileOnClick=e.getPath().getParentPath().toString();
                    }
                });
        }
    private void launchFile(loadTreeFileDevice.FileTreeNode node) {
                try {
                        File tempFile = new File(path, node.name);
                        //System.out.print(path);
                        //tempFile.deleteOnExit();
                        // ugly hack to call the method without FileEntry
                        Method m = device.getSyncService().getClass().getDeclaredMethod("doPullFile", String.class, String.class, SyncService.ISyncProgressMonitor.class);
                        m.setAccessible(true);
                        m.invoke(device.getSyncService(), node.pathFileTN, tempFile.getAbsolutePath(), device.getSyncService().getNullProgressMonitor());
                        //Desktop.getDesktop().open(tempFile);
                } catch(IOException ex) {output=output+ex+"\n";
                                jTextAreaStatus.setText(output);                  
                } catch (IllegalAccessException ex) {output=output+ex+"\n";
                                jTextAreaStatus.setText(output);
                } catch (IllegalArgumentException ex) {output=output+ex+"\n";
                                jTextAreaStatus.setText(output);
                } catch (NoSuchMethodException ex) {output=output+ex+"\n";
                                jTextAreaStatus.setText(output);
                } catch (SecurityException ex) {output=output+ex+"\n";
                                jTextAreaStatus.setText(output);
                } catch (InvocationTargetException ex) {output=output+ex+"\n";
                                jTextAreaStatus.setText(output);
                }
        }
}
